﻿using ActivtyUI.App_Code;
using ActivtyUI.Filter;
using EmoneyWeiXinBLL;
using EmoneyWeiXinCommon;
using EmoneyWeiXinEntity;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace ActivtyUI.Controllers
{
    public class DailyTaskController : Controller
    {
        string prefix1 = "DailyTaskZpResult";
        string key0032 = Config.MemcachedKey + "tenTimes" + System.DateTime.Now.ToString("yyyyMMdd");  //每日10次限制的key
        MemcachedTools1 mmtools = new MemcachedTools1();
        weixinUserEntity wxInfo
        {
            get
            {
                weixinUserEntity temp = new weixinUserEntity
                {

                    AppId = "wx25bf1ed19bab0096",
                    AppSecret = "d1067af0669ab1d98ee27adad3f98c5c",
                };
                return temp;
            }

        }
        #region  签到页面相关

        // GET: /DailyTask/
        /// <summary>
        /// 签到页面
        /// </summary>
        /// <returns></returns>
        [WeiXinUserAgentFilter]
        public ActionResult SignPage()
        {
            if (Request["openid"] == null)
            {
                return Content("缺少参数！");
            }
            string openid = Request["openid"];
            string weixinId = Request["weixinId"];
            ViewBag.openid = openid;
            ViewBag.weixinId = weixinId;
            InitSharas(Request.RawUrl);
            return View();
        }

        /// <summary>
        /// 根据openid获取已经签到的日期
        /// </summary>
        /// <returns></returns>
        public ActionResult GetSignedDateByOpenid()
        {
            string openid = Request["openid"];
            string weixinId = Request["weixinId"];
            List<string> list;
            list = DailyTaskBLL.GetSignDateByOpenId(openid);
            int SignCount = list.Count;//总签到天数
            int Consecutive = 0;

            if (list.Count > 0)
            {
                if ((DateTime.Now - Convert.ToDateTime(list[0])).Days > 1) //如果大于1,说明今天或者昨天没有签到
                {
                    Consecutive = 0;
                }
                else
                {
                    Consecutive = 1;
                    for (int i = 1; i < list.Count; i++)
                    {
                        if ((Convert.ToDateTime(list[i]) - Convert.ToDateTime(list[i - 1])).Days == -1)
                        {
                            Consecutive++;
                        }
                        else
                        {
                            break;
                        }
                    }
                }
            }

            //获取用户头像和昵称

            WXUserEntity userInfo = WXUserBLL.GetWxuserByOpenId2(openid);
            string userName = string.Empty;
            string img = string.Empty;
            if (userInfo != null)
            {
                userName = userInfo.nickname;
                img = userInfo.headimgurl;
            }
            else
            {
                userName = "";
                img = "~/images/DailyTask/img.jpg";
            }
            var jsonObj = new { list = list, lxQd = Consecutive, SignCount = SignCount, userName = userName, img = img };


            return Content(JsonTools.ToJson(jsonObj));

        }

        /// <summary>
        /// 执行签到动作
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult DoSign()
        {
            try
            {
                string openid = Request["openid"];
                string weixinId = Request["weixinId"];
                if (string.IsNullOrEmpty(weixinId))
                {
                    weixinId = "8";
                }
                DailyTaskEntity entity = new DailyTaskEntity();
                entity.openid = openid;
                entity.TaskType = 1;
                entity.ydGold = 20;
                entity.ReportId = -1;

                entity.weixinId = weixinId;
                int count = DailyTaskBLL.AddOneDailyTask(entity);
                if (count == 2)
                {
                    return Content("1");
                }
                else
                {
                    return Content("签到失败，或者你今天已经签到");
                }
            }
            catch (Exception)
            {
                return Content("0");
            }
        }

        #endregion

        #region   抽奖页相关
        [WeiXinUserAgentFilter]
        public ActionResult GamePage()
        {
            if (string.IsNullOrEmpty(Request["openid"]))
            {
                return Content("缺少参数！");
            }
            string openid = Request["openid"];
            string weixinId = Request["weixinId"];
            ViewBag.weixinId = weixinId;
            ViewBag.openid = openid;
            string key = prefix1 + openid;
            if (mmtools.Get(key) != null)
            {
                ViewBag.ZjResult = mmtools.Get(key);
            }
            else
            {
                int result = GetResult();
                mmtools.Add(key, result, 24, 0, 0);
                ViewBag.ZjResult = result;
            }

            GoldUserEntity golduserInfo = DailyTaskBLL.GetGoldUser(openid);
            if (golduserInfo != null)
            {
                ViewBag.sumGold = golduserInfo.SumGold;
            }
            else
            {
                ViewBag.sumGold = 0;
            }
            InitSharas(Request.RawUrl);
            return View();
        }

        /// <summary>
        /// 转盘游戏结果接收
        /// </summary>
        [HttpPost]
        [WeiXinUserAgentFilter]
        [ValidateAntiForgeryToken]
        public ActionResult ZpGameResultReceipt()
        {
            int zcResult = 1;
            try
            {
                string openid = Request["openid"];
                string result = Request["result"];
                if (int.Parse(result) < 1 || int.Parse(result) > 6)
                {
                    StringTools.GetSendMail("抽奖有人作弊！");
                    return Content("");
                }
                int syGold = 0;
                int count = 0;
                string key = prefix1 + openid;
                object resultObj = mmtools.Get(key);
                if (resultObj != null)
                {
                    result = resultObj.ToString();
                }
                double money = ResultMapMoney(int.Parse(result));
                #region  为再次抽奖准备结果
                zcResult = GetResult();
                mmtools.Add(key, zcResult, 24, 0, 0);
                #endregion
                int pagGold = ResultMapPayGold(int.Parse(result));
                count = DailyTaskBLL.AddDailyTaskZjJilu(openid, "zhuanpan", result, 500, money, out syGold);
                var returnObj = new { succss = (count == 3 ? 1 : 0), syGold = syGold, zcResult = zcResult };
                string json = JsonTools.ToJson(returnObj);
                return Content(json);
            }
            catch (Exception)
            {
                var returnObj = new { succss = 0, syGold = 0, zcResult = zcResult };
                string json = JsonTools.ToJson(returnObj);
                return Content(json);
            }

        }

        /// <summary>
        /// 中奖结果对应的钱
        /// </summary>
        /// <param name="result"></param>
        /// <returns></returns>
        public double ResultMapMoney(int result)
        {
            //10元以上的话费
            double[] money = { 0.1, 0, 5, 2, 1, 0.5, 10, 20, 30, 50, 100 };
            return money[result - 1];
        }

        /// <summary>
        /// 中奖结果对应所花费的金币
        /// </summary>
        /// <returns></returns>
        public int ResultMapPayGold(int result)
        {

            int[] money = { 500, 500, 500, 500, 500, 500, 1000, 2000, 3000, 5000, 10000 };
            return money[result - 1];
        }

        private int GetResult()
        {

            if (System.Configuration.ConfigurationManager.AppSettings["isSendRedpack"] == "0") { return 2; }
            Random r = new Random();
            int i = 2;
            if (System.DateTime.Now.Hour < 8 || System.DateTime.Now.Hour > 22) //当时间小于8点大于22点，中奖结果只能是1角或者没中奖
            {
                i = r.Next(1, 3);
                return i;
            }
            else
            {
                int value = r.Next(1, 101);
                if (value >= 1 && value <= 30)  //30%的机会中一毛
                {
                    return 1;
                }
                if (value > 30 && value <= 50) //20%的机会不中奖
                {
                    return 2;
                }
                if (value > 50 && value <= 80) //30%的中5毛
                {
                    return 6;
                }
                if (value > 80 && value <= 90) //10%的中1块
                {
                    return 5;
                }
                if (value > 90 && value <= 98) //8%的中2块
                {
                    return 4;
                }
                if (value > 98 && value <= 100) //2%的中5块
                {
                    return 3;
                }
            }
            return i;
        }

        [HttpPost]
        public ActionResult TiXian()
        {
            string openid = Request["openid"];
            string weixinId = Request["weixinId"];
            if (string.IsNullOrEmpty(openid) || string.IsNullOrEmpty(weixinId))
            {
                return Content("缺少参数");
            }
            string actName = "";
            if (weixinId == "8")
            {
                actName = "DailyTaskHGP";
            }
            else if (weixinId == "15")
            {
                actName = "DailyTask2GSZX";
            }
            else if (weixinId == "14")
            {
                actName = "DailyTaskAGCS";
            }
            string message = DailyTaskBLL.TiXian(openid, weixinId, ActCommon.GetSendRedPackConfigByActName(actName));
            return Content(message);
        }
        #endregion

        #region 金币流水页面
        [WeiXinUserAgentFilter]
        public ActionResult DailyTaskRecordPage()
        {
            if (string.IsNullOrEmpty(Request["openid"]))
            {
                return Content("缺少参数！");
            }
            string openid = Request["openid"];
            //string openid = "otfN4swILSNk118JD79CyXkZs4IY";
            ViewBag.openid = openid;

            GoldUserEntity golduserInfo = DailyTaskBLL.GetGoldUser(openid);
            if (golduserInfo != null)
            {
                ViewBag.SumGold = golduserInfo.SumGold;
            }
            InitSharas(Request.RawUrl);
            return View();
        }
        /// <summary>
        /// 获取金币流水的数据
        /// </summary>
        /// <returns></returns>
        [WeiXinUserAgentFilter]
        public ActionResult GetDailyTaskDataByPage()
        {
            string openid = Request["openid"];
            string page = Request["page"];
            int totalCount = 0;
            List<DailyTaskEntity> list = DailyTaskBLL.GetDailyTaskByPage(openid, int.Parse(page), out totalCount);
            int totalPage = (totalCount - 1) / 20 + 1;
            List<string> listStr = new List<string>();
            foreach (DailyTaskEntity item in list)
            {
                listStr.Add(item.CreateTime.ToString("yyyy.MM.dd") + TaskTypeMapToString(item.TaskType) + "" + item.GoldNum + "金币");
            }
            var jsonObj = new { list = listStr, totalPage = totalPage };
            string jsonStr = JsonTools.ToJson(jsonObj);
            return Content(jsonStr);
        }

        private string TaskTypeMapToString(int taskType)
        {
            switch (taskType)
            {
                case 1: return "签到获得";
                case 2: return "分享朋友圈获得";
                case 3: return "阅读文章获得";
                case 4: return "抽奖花费";
                default: return "";
            }
        }
        #endregion

        #region  资金流水页面
        public ActionResult GoldUserTradingRecordPage()
        {

            if (string.IsNullOrEmpty(Request["openid"]))
            {
                return Content("缺少参数！");
            }
            string openid = Request["openid"];
            string weixinId = Request["weixinId"];
            // string openid = "otfN4swILSNk118JD79CyXkZs4IY";
            ViewBag.openid = openid;
            ViewBag.weixinId = Request["weixinId"];
            GoldUserEntity golduserInfo = DailyTaskBLL.GetGoldUser(openid);
            if (golduserInfo != null)
            {
                ViewBag.Balance = golduserInfo.Balance;
            }
            InitSharas(Request.RawUrl);
            return View();
        }

        public ActionResult GetGoldUserTradingData()
        {
            string openid = Request["openid"];
            string page = Request["page"];
            int totalCount = 0;
            List<GoldUserTradingRecordEntity> list = DailyTaskBLL.GetTradingRecordListByPage(openid, int.Parse(page), out totalCount);
            int totalPage = (totalCount - 1) / 20 + 1;
            List<string> listStr = new List<string>();
            foreach (GoldUserTradingRecordEntity item in list)
            {
                listStr.Add(item.CreateTime.ToString("yyyy.MM.dd") + (item.Direction == 1 ? "中奖" : "提现") + item.ActiveMoney + "元");
            }
            var jsonObj = new { list = listStr, totalPage = totalPage };
            string jsonStr = JsonTools.ToJson(jsonObj);
            return Content(jsonStr);
        }
        #endregion

        #region   金币规则
        public ActionResult GetGoldRole()
        {
            return View();
        }

        public ActionResult GetGoldRole2()
        {
            if (string.IsNullOrEmpty(Request["openid"]))
            {
                return Content("缺少参数！");
            }
            string openid = Request["openid"];
            string weixinId = Request["weixinId"];
            ViewBag.weixinId = weixinId;
            ViewBag.openid = openid;
            InitSharas(Request.RawUrl);
            return View();
        }

        [WeiXinUserAgentFilter]
        public ActionResult Index()
        {

            if (string.IsNullOrEmpty(Request["openid"]))
            {
                return Content("缺少参数！");
            }
            string openid = Request["openid"];
            string weixinId = Request["weixinId"];
            if (string.IsNullOrEmpty(weixinId))
            {
                weixinId = "8";
            }
            ViewBag.openid = openid;
            ViewBag.weixinId = weixinId;
            DataTable dt = DailyTaskBLL.GetUserMainInfo(openid);
            ViewBag.Data = dt;
            InitSharas(Request.RawUrl);
            return View();
        }
        #endregion

        #region 活动统计页面
        public ActionResult TjPage()
        {
            DataTable dt = DailyTaskBLL.GetTjData();
            ViewBag.Data = dt;
            return View();
        }
        #endregion


        #region  积分兑换话费的

        /// <summary>
        /// 话费兑换页面
        /// </summary>
        /// <returns></returns>
        public ActionResult GamePage2()
        {

            if (System.Configuration.ConfigurationManager.AppSettings["isactOpen001"] == "1")
            {
                if (string.IsNullOrEmpty(Request["openid"]))
                {
                    return Content("缺少参数！");
                }
                string openid = Request["openid"];
                string weixinId = Request["weixinId"];
                ViewBag.weixinId = weixinId;
                ViewBag.openid = openid;
                GoldUserEntity golduserInfo = DailyTaskBLL.GetGoldUser(openid);
                if (golduserInfo != null)
                {
                    ViewBag.sumGold = golduserInfo.SumGold;
                }
                InitSharas(Request.RawUrl);
                return View();
            }
            else
            {
                return Content("活动还在测试中，明日开启，敬请期待");
            }
        }



        /// <summary>
        /// 积分兑换结果
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [WeiXinUserAgentFilter]
        [ValidateAntiForgeryToken]
        public ActionResult DuiHuanResultReceipt()
        {
            try
            {
                if (System.DateTime.Now.Hour > 19 || System.DateTime.Now.Hour < 8)
                {
                    var returnObj = new { succss = 0, msg = "抱歉！兑换时间为每日的8点至19点之间！" };
                    return Content(JsonTools.ToJson(returnObj));
                }
                string openid = Request["openid"];
                string result = Request["result"];
                if (int.Parse(result) < 7 || int.Parse(result) > 11)
                {
                    StringTools.GetSendMail("话费兑换有人作弊");
                    return Content("");
                }
                if (result == "7")  //10元话费
                {
                    long c = CacheManager.RedisCache.Get<long>(key0032);
                    if (c >= 10)
                    {
                        var returnObj = new { succss = 0, msg = "今日兑换次数已有10次，明日再来吧" };
                        string json = JsonTools.ToJson(returnObj);
                        return Content(json);
                    }
                    else
                    {
                        long ret = CacheManager.RedisCache.Increment(key0032, 1);
                        if (ret > 10)
                        {
                            CacheManager.RedisCache.Decrement(key0032, 1);
                            var returnObj = new { succss = 0, msg = "今日兑换次数已有10次，明日再来吧" };
                            string json = JsonTools.ToJson(returnObj);
                            return Content(json);
                        }
                    }
                }
                int syGold = 0;
                int count = DailyTaskBLL.AddDailyTaskZjJilu(openid, "duihuafei", result, ResultMapPayGold(int.Parse(result)), ResultMapMoney(int.Parse(result)), out syGold);
                var returnObj2 = new { succss = (count == 3 ? 1 : 0), syGold = syGold };
                string json2 = JsonTools.ToJson(returnObj2);
                return Content(json2);

            }
            catch (Exception)
            {
                var returnObj = new { succss = 0, syGold = 0 };
                string json2 = JsonTools.ToJson(returnObj);
                return Content(json2);
            }

        }

        public ActionResult ZhuanQian()
        {
            if (string.IsNullOrEmpty(Request["openid"]))
            {
                return Content("缺少参数！");
            }
            string openid = Request["openid"];
            string weixinId = Request["weixinId"];
            ViewBag.weixinId = weixinId;
            ViewBag.openid = openid;
            InitSharas(Request.RawUrl);

            #region
            string key = StringTools.ChangeRealKey("newsreport", weixinId + "haogu");
            object jsonStr = mmtools.Get(key);
            if (jsonStr != null)
            {
                var query = JsonTools.ToObject<NewsReportEntity>(jsonStr.ToString());
                if (query != null)
                {
                    string newUrl = Config.selNewsReportUrl + "?fn=" + openid + "&weixinid=" + weixinId + "&id=" + query.ID + "&Ntype=" + "haogu";
                    ViewBag.newUrl = newUrl;
                }
            }
            else
            {
                string newUrl = string.Format("http://mobilehuoke.emoney.cn/WXOpen/NewsReport?fn={0}&weixinid={1}&id=60436&Ntype=haogu", openid, weixinId);
                ViewBag.newUrl = newUrl;
            }
            #endregion



            return View();
        }

        #endregion


        private void InitSharas(string rawUrl)
        {
            var timestamp = WeiXinJsSign.getTimestamp();
            var nonceStr = WeiXinJsSign.getNoncestr();
            ViewBag.timestamp = timestamp;
            ViewBag.nonceStr = nonceStr;
            ViewBag.appid = this.wxInfo.AppId;
            ViewBag.appsecret = this.wxInfo.AppSecret;
            string url = Config.Host_Url2 + rawUrl;
            ViewBag.signature = WeiXinJsSign.getWxSign(nonceStr, timestamp, this.wxInfo, url);
        }
    }
}
